package com.bf.electroplating.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bf.electroplating.mapper.SewageWarningConfigMapper;
import com.bf.electroplating.pojo.dto.contingencyplan.ComContingencyPlanDTO;
import com.bf.electroplating.pojo.dto.contingencyplan.ComContingencyPlanQueryDTO;
import com.bf.electroplating.pojo.entity.ComCompany;
import com.bf.electroplating.pojo.entity.ComContingencyPlan;
import com.bf.electroplating.pojo.entity.PubParamDictionary;
import com.bf.electroplating.pojo.entity.SewageWarningConfig;
import com.bf.electroplating.pojo.enums.AttModuleEnums;
import com.bf.electroplating.pojo.enums.DicTypeEnums;
import com.bf.electroplating.pojo.vo.ResultVO;
import com.bf.electroplating.pojo.vo.SelectVo;
import com.bf.electroplating.pojo.vo.WasteWaterTypeVO;
import com.bf.electroplating.pojo.vo.contingencyplan.ComContingencyPlanVO;
import com.bf.electroplating.pojo.vo.sewageWarningConfig.SewageWarningDTO;
import com.bf.electroplating.pojo.vo.sewageWarningConfig.SewageWarningQueryDTO;
import com.bf.electroplating.pojo.vo.sewageWarningConfig.SewageWarningVO;
import com.bf.electroplating.service.ComCompanyService;
import com.bf.electroplating.service.ISewageWarningConfigService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bf.electroplating.service.PubAttachmentService;
import com.bf.electroplating.service.PubParamDictionaryService;
import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.messaging.handler.annotation.support.MethodArgumentNotValidException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 污水预警管理表 服务实现类
 * </p>
 *
 * @author gzd
 * @since 2025-08-21
 */
@Service
public class SewageWarningConfigServiceImpl extends ServiceImpl<SewageWarningConfigMapper, SewageWarningConfig> implements ISewageWarningConfigService {

    @Resource
    private ComCompanyService comCompanyService;

    @Resource
    private PubAttachmentService pubAttachmentService;
    @Resource
    private PubParamDictionaryService pubParamDictionaryService;

    @Override
    public ResultVO < Page < SewageWarningVO > > pageList ( SewageWarningQueryDTO queryDTO ) {
        Page < SewageWarningConfig > page = new Page <> ( queryDTO.getPageNum () , queryDTO.getPageSize () );
        LambdaQueryWrapper < SewageWarningConfig > wrapper = new LambdaQueryWrapper <> ();
        if ( StringUtils.isNotBlank ( queryDTO.getCompanyId () ) ) {
            wrapper.eq ( SewageWarningConfig::getCompanyId , queryDTO.getCompanyId () );
        }
        if ( StringUtils.isNotBlank ( queryDTO.getWasteWaterType () ) ) {
            wrapper.like ( SewageWarningConfig::getWasteWaterType , queryDTO.getWasteWaterType () );
        }
        wrapper.orderByDesc ( SewageWarningConfig::getCreateTime );
        Page < SewageWarningConfig > resultPage = this.page ( page , wrapper );
        // 转换为VO
        Page < SewageWarningVO > voPage = new Page <> ();
        BeanUtils.copyProperties ( resultPage , voPage , "records" );
        List < SewageWarningVO > voList = new ArrayList <> ();
        for ( SewageWarningConfig entity : resultPage.getRecords () ) {
            SewageWarningVO vo = new SewageWarningVO ();
            BeanUtils.copyProperties ( entity , vo );
            vo.setWasteWaterType(pubParamDictionaryService.getNameByModuleAndCode(DicTypeEnums.FSLX.getCode(),entity.getWasteWaterType()));
            vo.setWarnValue(getWarnValue(vo));
            voList.add ( vo );
        }
        voPage.setRecords ( voList );
        return ResultVO.ok ( voPage );
    }

    private String getWarnValue(SewageWarningVO vo) {
        StringBuilder sb = new StringBuilder();
        if ("1".equals(vo.getMonitorHexavalentChromium())){
            sb.append("六价铬：").append(vo.getHexavalentChromiumThreshold()).append(",");
        }
        if ("1".equals(vo.getMonitorTotalChromium())){
            sb.append("总铬：").append(vo.getTotalChromiumThreshold()).append(",");
        }
        if ("1".equals(vo.getMonitorTotalNickel())){
            sb.append("总镍：").append(vo.getTotalNickelThreshold()).append(",");
        }
        return sb.toString();
    }

    @Override
    @Transactional ( rollbackFor = Exception.class )
    public ResultVO < String > saveData ( SewageWarningDTO dto ) {
        SewageWarningConfig sewageWarning = new SewageWarningConfig ();
        if (!"1".equals( dto.getMonitorHexavalentChromium() )
                &&!"1".equals( dto.getMonitorTotalChromium() )
        &&!"1".equals( dto.getMonitorTotalNickel() ) ) {
            return ResultVO.fail ( "预警因子必须选择其一" );
        }
        if (!StringUtils.isEmpty( dto.getId()) ) {
          long count=this.count(new LambdaQueryWrapper<SewageWarningConfig>()
                  .eq(SewageWarningConfig::getCompanyId,dto.getCompanyId ())
                  .eq(SewageWarningConfig::getWasteWaterType,dto.getWasteWaterType()));
            if (count > 0) {
                return ResultVO.fail("一家公司同一种污水处理标准只能设置一次");
            }
        }
        BeanUtils.copyProperties ( dto , sewageWarning );
        saveOrUpdate ( sewageWarning );

        return ResultVO.ok ( null , "保存成功" );
    }

    @Override
    @Transactional ( rollbackFor = Exception.class )
    public ResultVO < String > delete ( List < String > ids ) {
        if ( ids == null || ids.isEmpty () ) {
            return ResultVO.fail ( "ID不能为空" );
        }

        this.removeByIds ( ids );
        return ResultVO.ok ( null , "删除成功" );
    }

    @Override
    public ResultVO < SewageWarningVO > getDetail ( String id ) {
        if ( StringUtils.isBlank ( id ) ) {
            return ResultVO.fail ( "ID不能为空" );
        }
        SewageWarningConfig entity = this.getById ( id );
        if ( entity == null ) {
            return ResultVO.fail ( "记录不存在" );
        }

        Map < String,String > companyMap = comCompanyService.list ().stream ().collect ( Collectors.toMap ( ComCompany::getId , ComCompany::getCompanyName ) );

        SewageWarningVO vo = new SewageWarningVO ();
        BeanUtils.copyProperties ( entity , vo );
        vo.setCompanyName ( companyMap.get ( entity.getCompanyId () ) );

        return ResultVO.ok ( vo );
    }

    @Override
    public ResultVO<List<WasteWaterTypeVO>> getWasteWaterTypeByCompanyId(String companyId) {
        List<SewageWarningConfig> voList = this.list(new LambdaQueryWrapper<SewageWarningConfig>()
                .eq(SewageWarningConfig::getCompanyId,companyId));
        if (!CollectionUtils.isEmpty(voList)) {
            List<WasteWaterTypeVO> wasteWaterTypeVOS=new ArrayList<>();
            List<String> types=voList.stream().map(SewageWarningConfig::getWasteWaterType).collect ( Collectors.toList () );
            List<SelectVo> pubParamDictionaries=pubParamDictionaryService.getParamList(DicTypeEnums.FSLX.getCode()).getData();
            Map<String,String> map=pubParamDictionaries.stream().collect(Collectors.toMap(SelectVo::getId,SelectVo::getName));
            wasteWaterTypeVOS=types.stream().map(i->{
                WasteWaterTypeVO vo=new WasteWaterTypeVO ();
                vo.setWasteWaterTypeCode(i);
                vo.setWasteWaterTypeName ( map.get (i) );
                return vo;
            }).collect ( Collectors.toList () );
            return ResultVO.ok ( wasteWaterTypeVOS );
        }
        return  ResultVO.ok (new ArrayList<>());
    }

    @Override
    public ResultVO<List<SewageWarningVO>> getListByCompanyAndWasterType(String companyId, String wasterType) {
        LambdaQueryWrapper < SewageWarningConfig > wrapper = new LambdaQueryWrapper <> ();
            wrapper.eq ( SewageWarningConfig::getCompanyId , companyId );
            wrapper.like ( SewageWarningConfig::getWasteWaterType , wasterType );
        wrapper.orderByDesc ( SewageWarningConfig::getCreateTime );
        List < SewageWarningConfig > resultPage = this.list (  wrapper );
        // 转换为VO
        List < SewageWarningVO > voList = new ArrayList <> ();
        for ( SewageWarningConfig entity : resultPage ) {
            SewageWarningVO vo = new SewageWarningVO ();
            BeanUtils.copyProperties ( entity , vo );
            vo.setWasteWaterType(pubParamDictionaryService.getNameByModuleAndCode(DicTypeEnums.FSLX.getCode(),entity.getWasteWaterType()));
            vo.setWarnValue(getWarnValue(vo));
            voList.add ( vo );
        }
        return ResultVO.ok ( voList );
    }
}
